package com.jb.repair.adapter;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.RS.AndroidSDK.HardwareCtrl;
import com.jb.repair.R;
import com.jb.repair.acticity.BatchDealActivity;
import com.jb.repair.acticity.BugRegisterActivity;
import com.jb.repair.acticity.ChangeRegisterActivity;
import com.jb.repair.acticity.CheckRegisActivity;
import com.jb.repair.common.Constants;
import com.jb.repair.dao.ModifyDb;
import com.jb.repair.model.ItemModel;
import com.jb.repair.model.ResultModel;
import com.jb.repair.util.MessageUtil;
import com.jb.util.StringUtils;

import java.util.List;

/**
 * Created by gaobin on 2015/11/2.
 */
public class CheckRegisChildAdapter extends BaseAdapter {
    private Context mContext;
    private List<ItemModel> mData;
    private LayoutInflater mInflater;
    private String devName;
    private String TAG = "CheckRegisChildAdapter";
    private String equip_id;
    private int pos;
    private int cycle;
    private Boolean isBatch;
    private boolean jumpFromTag;
    private boolean stop = true;//是否停止传感器
    SharedPreferences sp;



    //cycle 0 每天一次  1 每周一次 2 每月一次 3 每周两次 4 每周三次 5 每月2次
    public CheckRegisChildAdapter(Context mContext, List<ItemModel> mData, String devName, String id, int position, int cycle, Boolean isBatch, boolean jumpFromTag) {
        this.mContext = mContext;
        this.mData = mData;
        mInflater = LayoutInflater.from(mContext);
        this.devName = devName;
        this.equip_id = id;
        this.pos = position;
        this.cycle = cycle;
        this.isBatch = isBatch;
        this.jumpFromTag = jumpFromTag;
        sp = mContext.getSharedPreferences(Constants.SP_NAME, mContext.MODE_PRIVATE);
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        convertView = mInflater.inflate(R.layout.item_check_info, null);
        TextView tv_project = (TextView) convertView.findViewById(R.id.tv_project_name);
        TextView tv_content = (TextView) convertView.findViewById(R.id.tv_content);
        TextView tv_standard = (TextView) convertView.findViewById(R.id.tv_stardand);
        final TextView tv_res = (TextView) convertView.findViewById(R.id.tv_result);
        TextView tv_no = (TextView) convertView.findViewById(R.id.tv_no);
        ImageView iv_imp = (ImageView) convertView.findViewById(R.id.iv_imp);
        TextView tv_predate = (TextView) convertView.findViewById(R.id.tv_pre_check_date);

        final ItemModel model = mData.get(position);


        if (model.isMust)
            iv_imp.setVisibility(View.VISIBLE);
        else
            iv_imp.setVisibility(View.INVISIBLE);
        tv_project.setText(model.position);
        tv_content.setText(model.content);
        tv_res.setText(model.checkResult);
        tv_no.setText((position + 1) + "");
        if (model.checkResult.equals("正常") || model.checkResult.equals("未检查"))
            tv_res.setTextColor(mContext.getResources().getColor(R.color.main_textcolor));
        else if (model.checkResult.equals("异常")) {
            tv_res.setTextColor(mContext.getResources().getColor(R.color.chart_red));
        } else if (model.method.equals("0401902")) {//测量
            Float num_result = 0f;
            try {
                // 去掉单位
                String checkResultWithNoUnit = unescape(model.checkResult);
                num_result = Float.parseFloat(checkResultWithNoUnit.equals("")?"0":checkResultWithNoUnit);
            } catch (Exception e) {
                e.printStackTrace();
            }


            // 根据是否超过最大最小范围，设定字体颜色
            boolean valid = true; // 初始化，数据合法，未超出最大最小范围
            // 判定是否超出最大范围
            if (StringUtils.isNotBlank(model.standard_max)) {
                if (num_result > Float.parseFloat(model.standard_max)) {
                    valid = false;
                }
            }
            // 判定是否超出最小范围
            if (StringUtils.isNotBlank(model.standard_min)) {
                if (num_result < Float.parseFloat(model.standard_min)) {
                    valid = false;
                }
            }
            // 未超过最大最小范围，显示黑色字体
            if (valid) {
                tv_res.setTextColor(mContext.getResources().getColor(R.color.black_text));
            } else { // 超出合法范围，显示红色
                tv_res.setTextColor(mContext.getResources().getColor(R.color.chart_red));
            }

        }
        tv_predate.setText(model.preCheckDate);
        tv_standard.setText(model.standard);
//        tv_res.setEnabled(CheckRegisActivity.changable);
        if (!CheckRegisActivity.changable) {
            tv_predate.setVisibility(View.GONE);
        }

        tv_res.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CheckRegisParentAdapter.IS_HISTORY) {
                    MessageUtil.showToast(mContext, "历史任务不能再进行结果登记");
                    return;
                }

                if (!jumpFromTag) {
                    MessageUtil.showToast(mContext, "请返回上一层界面，扫描标签后方可登记结果");
                    return;
                }

                if (model.method.equals("0401901")) {//目视
                    if (model.checkResult.equals("正常")) {
                        showRegisPop((TextView) v, position, 0);
                    } else if (model.checkResult.equals("异常")) {
                        showRegisPop((TextView) v, position, 1);
                    } else if (model.checkRes == 0) {
                        showSelectPop(tv_res, position);
                    }
                } else if (model.method.equals("0401902")) {//测量类
                    Float num_result = 0f;
                    try {
                        num_result = Float.parseFloat(model.checkResult);
                        if (mData.get(position).checkResult == null || mData.get(position).checkResult.equals("未检查"))
                            showRegisNumPop(tv_res, position);

                        else if (StringUtils.isNotBlank(mData.get(position).standard_min) && num_result < Float.parseFloat(mData.get(position).standard_min))
                            showRegisPop((TextView) v, position, 2);
                        else if (StringUtils.isNotBlank(mData.get(position).standard_max) && num_result > Float.parseFloat(mData.get(position).standard_max))
                            showRegisPop((TextView) v, position, 3);
                        else
                            showRegisNumPop(tv_res, position);
                    } catch (Exception e) {
                        showRegisNumPop(tv_res, position);
                    }

                }
            }
        });

        return convertView;
    }

    /**
     * 登记数值类结果
     *
     * @param tv
     * @param position
     */
    private void showRegisNumPop(final TextView tv, final int position) {   //弹出数值登记的对话框
        View popView = mInflater.inflate(R.layout.pop_regist_num_item, null);
        final PopupWindow pop = new PopupWindow(popView, (int) mContext.getResources().getDimension(R.dimen.x400), (int) mContext.getResources().getDimension(R.dimen.y300), true);
        pop.setFocusable(true);
        ColorDrawable dw = new ColorDrawable(0x00000000);
        pop.setBackgroundDrawable(dw);
        pop.showAtLocation(tv, Gravity.CENTER, 0, 0);
        final EditText et = (EditText) popView.findViewById(R.id.et_input_num);
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    default:
                        String reading = msg.getData().getString("data");
                        Log.i(TAG, "reading = " + reading);
                        et.setText(reading);
                        break;
                }
            }
        };
        //判断是否开启测温测振
        if (sp.getBoolean(Constants.SWITCH_MEASURE, false)) {
            //根据单位开启测温测振功能
            String unit = mData.get(position).tools;
            if (unit == null)
                unit = "";
            Log.i(TAG, "单位为:" + unit);
            if ("0401403".equals(unit)) {
                //测量温度
                //开启传感器
                Log.i(TAG, "开启温度传感器");
                new MeasureThread(0, handler).start();

            } else if ("0401402".equals(unit)) {
                //测量振动
                Log.i(TAG, "开启振动传感器");
                new MeasureThread(1, handler).start();
            }
        }


        popView.findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() { //登记数值类结果
            @Override
            public void onClick(View v) {
                //关闭传感器
                stop = false;

                String resut = et.getText().toString();
                resut = unescape(resut); // 去掉单位
                if (resut == null || resut.equals("")) {
                    Toast.makeText(mContext, "输入数据不正确，请重新输入", Toast.LENGTH_SHORT).show();
                    return;
                }
                ItemModel model = mData.get(position);
                ResultModel resultModel = new ResultModel();
                resultModel.GUID = model.resultId;
                resultModel.num_result = resut;
                resultModel.is_must_today = model.isMust ? "T" : "F";

                // 根据是否超过最大最小范围，设定登记结果
                boolean valid = true; // 初始化，数据合法，未超出最大最小范围
                // 判定是否超出最大范围
                if (StringUtils.isNotBlank(mData.get(position).standard_max)) {
                    if (Float.parseFloat(resut) > Float.parseFloat(mData.get(position).standard_max)) {
                        valid = false;
                    }
                }
                // 判定是否超出最小范围
                if (StringUtils.isNotBlank(mData.get(position).standard_min)) {
                    if (Float.parseFloat(resut) < Float.parseFloat(mData.get(position).standard_min)) {
                        valid = false;
                    }
                }

                resultModel.is_abnormal = valid ? "F" : "T";

                ModifyDb.getInstance(mContext).regisNum(resultModel);
                update(position, resut);
                pop.dismiss();
            }
        });
        popView.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() { //登记数值类结果
            @Override
            public void onClick(View v) {
                //关闭传感器
                stop = false;
                pop.dismiss();
            }
        });
    }

    private void showSelectPop(final View v2, final int position) {
        final TextView tv = (TextView) v2;
        View popView = mInflater.inflate(R.layout.pop_abnormal, null);
        final PopupWindow pop = new PopupWindow(popView, (int) mContext.getResources().getDimension(R.dimen.x80), (int) mContext.getResources().getDimension(R.dimen.y100), true);
        pop.setFocusable(true);
        ColorDrawable dw = new ColorDrawable(0x00000000);
        pop.setBackgroundDrawable(dw);
        pop.showAsDropDown(tv, -(int) mContext.getResources().getDimension(R.dimen.x50), -(int) mContext.getResources().getDimension(R.dimen.y65));
        popView.findViewById(R.id.tv_normal).setOnClickListener(new View.OnClickListener() { //异常登记
            @Override
            public void onClick(View v) {  //登记观测类 正常
                ItemModel model = mData.get(position);
                ResultModel resultModel = new ResultModel();
                resultModel.GUID = model.resultId;
                resultModel.is_defect = "F";
                resultModel.is_abnormal = "F";
                resultModel.is_must_today = model.isMust ? "T" : "F";
                ModifyDb.getInstance(mContext).regist(resultModel);
                update(position, "正常");
                pop.dismiss();
            }
        });

        popView.findViewById(R.id.tv_abnormal).setOnClickListener(new View.OnClickListener() { //异常登记
            @Override
            public void onClick(View v) {
                update(position, "异常");
               /* ItemModel model = mData.get(position);
                ResultModel resultModel = new ResultModel();
                resultModel.GUID = model.resultId;
                resultModel.is_defect = "F";
                resultModel.is_abnormal = "T";
                resultModel.is_must_today = model.isMust ? "T" : "F";
                ModifyDb.getInstance(mContext).registAbnormal(resultModel);*/
                pop.dismiss();
            }
        });
    }

    private void showRegisPop(final TextView view, final int position, int b) {
        View popView = mInflater.inflate(R.layout.pop_exception_regis, null);
        final PopupWindow pop = new PopupWindow(popView, (int) mContext.getResources().getDimension(R.dimen.x400), (int) mContext.getResources().getDimension(R.dimen.y250), true);
        pop.setFocusable(true);
        ColorDrawable dw = new ColorDrawable(0x00000000);
        pop.setBackgroundDrawable(dw);
        pop.showAtLocation(view, Gravity.CENTER, 0, 0);
        popView.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() { //关闭popview
            @Override
            public void onClick(View v) {
                pop.dismiss();
            }
        });
        TextView tv1 = (TextView) popView.findViewById(R.id.tv_abnormal_regis);
        TextView tv2 = (TextView) popView.findViewById(R.id.tv_error_regis);
        TextView tv3 = (TextView) popView.findViewById(R.id.tv_back);
        TextView tv4 = (TextView) popView.findViewById(R.id.tv_title);


        switch (b) {
            case 0:
                tv4.setVisibility(View.GONE);
                tv3.setVisibility(View.GONE);
                tv1.setText("撤销登记");
                tv2.setText("转为异常");
                tv1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        view.setTextColor(mContext.getResources().getColor(R.color.main_textcolor));
                        update(position, "未检查");
                        if (!isBatch) {
                            ModifyDb.getInstance(mContext).revokeRegis(mData.get(position).resultId);
                        }
                        pop.dismiss();
                    }
                });
                tv2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        view.setTextColor(mContext.getResources().getColor(R.color.main_textcolor));
                        update(position, "异常");
                        ItemModel model = mData.get(position);
                        ResultModel resultModel = new ResultModel();
                        resultModel.GUID = model.resultId;
                        resultModel.is_defect = "F";
                        resultModel.is_abnormal = "T";
                        resultModel.is_must_today = model.isMust ? "T" : "F";
                        ModifyDb.getInstance(mContext).registAbnormal(resultModel);
                        pop.dismiss();
                    }
                });
                break;
            case 1:
                tv4.setVisibility(View.GONE);
                tv3.setVisibility(View.VISIBLE);
                tv1.setText("登记异常");
                tv2.setText("登记缺陷");
                tv1.setOnClickListener(new View.OnClickListener() { //异常登记
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, ChangeRegisterActivity.class);
                        intent.putExtra("devName", devName);
                        intent.putExtra("itemName", mData.get(position).position);
                        intent.putExtra("resultId", mData.get(position).resultId);
                        intent.putExtra("planId", mData.get(position).planId);
                        intent.putExtra("equip_id", equip_id);
                        intent.putExtra("isMust",mData.get(position).isMust?"T":"F");
                        mContext.startActivity(intent);
                        pop.dismiss();
                    }
                });

                tv2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, BugRegisterActivity.class);
                        intent.putExtra("devName", devName);
                        intent.putExtra("itemName", mData.get(position).position);
                        intent.putExtra("resultId", mData.get(position).resultId);
                        intent.putExtra("planId", mData.get(position).planId);
                        intent.putExtra("equip_id", equip_id);
                        intent.putExtra("dev_id", equip_id);
                        intent.putExtra("isMust",mData.get(position).isMust?"T":"F");
                        mContext.startActivity(intent);
                        pop.dismiss();
                    }
                });

                tv3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        view.setTextColor(mContext.getResources().getColor(R.color.main_textcolor));
                        update(position, "未检查");
                        if (!isBatch) {
                            ModifyDb.getInstance(mContext).revokeRegis(mData.get(position).resultId);
                        }
                        pop.dismiss();
                    }
                });
                break;
            case 2:
                tv4.setVisibility(View.VISIBLE);
                tv3.setVisibility(View.VISIBLE);
                tv1.setText("登记异常");
                tv2.setText("登记缺陷");
                tv4.setText("低于正常范围最小值" + mData.get(position).standard_min + transformUnit(mData.get(position).unit));
                tv1.setOnClickListener(new View.OnClickListener() { //异常登记
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, ChangeRegisterActivity.class);
                        intent.putExtra("devName", devName);
                        intent.putExtra("itemName", mData.get(position).position);
                        intent.putExtra("resultId", mData.get(position).resultId);
                        intent.putExtra("planId", mData.get(position).planId);
                        intent.putExtra("equip_id", equip_id);
                        intent.putExtra("isMust",mData.get(position).isMust?"T":"F");
                        mContext.startActivity(intent);
                        pop.dismiss();
                    }
                });

                tv2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, BugRegisterActivity.class);
                        intent.putExtra("devName", devName);
                        intent.putExtra("itemName", mData.get(position).position);
                        intent.putExtra("resultId", mData.get(position).resultId);
                        intent.putExtra("planId", mData.get(position).planId);
                        intent.putExtra("equip_id", equip_id);
                        intent.putExtra("dev_id", equip_id);
                        intent.putExtra("isMust",mData.get(position).isMust?"T":"F");
                        mContext.startActivity(intent);
                        pop.dismiss();
                    }
                });

                tv3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        view.setTextColor(mContext.getResources().getColor(R.color.main_textcolor));
                        update(position, "未检查");
                        if (!isBatch) {
                            ModifyDb.getInstance(mContext).revokeRegis(mData.get(position).resultId);
                        }
                        pop.dismiss();
                    }
                });
                break;
            case 3:
                tv4.setVisibility(View.VISIBLE);
                tv3.setVisibility(View.VISIBLE);
                tv4.setText("超出正常范围最大值" + mData.get(position).standard_max + transformUnit(mData.get(position).unit));
                tv1.setText("登记异常");
                tv2.setText("登记缺陷");
                tv1.setOnClickListener(new View.OnClickListener() { //异常登记
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, ChangeRegisterActivity.class);
                        intent.putExtra("devName", devName);
                        intent.putExtra("itemName", mData.get(position).position);
                        intent.putExtra("resultId", mData.get(position).resultId);
                        intent.putExtra("planId", mData.get(position).planId);
                        intent.putExtra("equip_id", equip_id);
                        intent.putExtra("isMust",mData.get(position).isMust?"T":"F");
                        mContext.startActivity(intent);
                        pop.dismiss();
                    }
                });

                tv2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, BugRegisterActivity.class);
                        intent.putExtra("devName", devName);
                        intent.putExtra("itemName", mData.get(position).position);
                        intent.putExtra("resultId", mData.get(position).resultId);
                        intent.putExtra("planId", mData.get(position).planId);
                        intent.putExtra("equip_id", equip_id);
                        intent.putExtra("dev_id", equip_id);
                        intent.putExtra("isMust",mData.get(position).isMust?"T":"F");
                        mContext.startActivity(intent);
                        pop.dismiss();
                    }
                });

                tv3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        view.setTextColor(mContext.getResources().getColor(R.color.main_textcolor));
                        update(position, "未检查");
                        if (!isBatch) {
                            ModifyDb.getInstance(mContext).revokeRegis(mData.get(position).resultId);
                        }
                        pop.dismiss();
                    }
                });
                break;
        }
    }

    /**
     * 单位换算
     *
     * @param unit {String} 单位代号
     * @return 代号对应的单位
     */
    private String transformUnit(String unit) {
        // 摄氏度
        if ("0406701".equals(unit)) return "℃";
        // 千克
        if ("0406702".equals(unit)) return "KG";
        // 其他情况，单位为空
        return "";
    }

    /**
     * 去掉点检结果中可能存在的单位
     * 目前已知单位有KG和摄氏度
     *
     * @param result
     * @return
     */
    private String unescape(String result) {
        int index;
        // 去掉可能存在的KG
        index = result.toUpperCase().indexOf("KG");
        if (index > -1) {
            result = result.substring(0, index);
            return result;
        }
        // 去掉可能存在的℃
        index = result.toUpperCase().indexOf("℃");
        if (index > -1) {
            result = result.substring(0, index);
            return result;
        }

        return result;
    }

    public void update(int position, String result) {
        if (isBatch) {
            BatchDealActivity.update(pos, position, cycle, result);
        } else {
            CheckRegisActivity.update(pos, position, cycle, result);
        }
    }

    class MeasureThread extends Thread {

        private int type;//0-温度  1-振动
        private Handler handler;
        private String reading;//传感器读数

        public MeasureThread(int type, Handler handler) {
            this.type = type;
            this.handler = handler;
        }

        public void run() {
            switch (type) {
                case 0:
                    HardwareCtrl.IRTinit("");
                    while (stop) {
                        reading = HardwareCtrl.IRTread();
                        Log.i(TAG, "温度读数为：" + reading);
                        //更新到编辑框中
                        Bundle bd = new Bundle();//放在外面 有时更新ui会丢失数据
                        bd.putString("data", reading);
                        Message msg = new Message();
                        msg.what = 0;
                        msg.setData(bd);
                        handler.sendMessage(msg);
                    }
                    HardwareCtrl.IRTclose();
                    break;
                case 1:
                    HardwareCtrl.VIBinit(1, 0);
                    while (stop) {
                        reading = HardwareCtrl.VIBread();
                        Log.i(TAG, "振动读数为：" + reading);
                        //更新到编辑框中
                        Bundle bd = new Bundle();//放在外面 有时更新ui会丢失数据
                        bd.putString("data", reading);
                        Message msg = new Message();
                        msg.what = 1;
                        msg.setData(bd);
                        handler.sendMessage(msg);
                    }
                    HardwareCtrl.VIBclose();
                    break;

            }

        }
    }
}

